$(function () {
    layui.config({
        base: '../../statics/common/'
    }).extend({
        soulTable: 'layui/soultable/ext/soulTable.slim'
    });

    layui.use(['form','layedit', 'laydate', 'upload','soulTable'], function(){
        var form = layui.form,
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;
            form.verify({
                carNoVerify: function (value) {
                    if((vm.carRepairOrder.carNo =="" || vm.carRepairOrder.carNo==null) && (vm.carRepairOrder.vinNo =="" || vm.carRepairOrder.vinNo==null)){
                        return '请通过车牌号选择或者通过车架号选择车辆信息！';
                    }
                },
                vinNoVerify: function (value) {
                    if((vm.carRepairOrder.carNo =="" || vm.carRepairOrder.carNo==null) && (vm.carRepairOrder.vinNo =="" || vm.carRepairOrder.vinNo==null)){
                        return '请通过车牌号选择或者通过车架号选择车辆信息！';
                    }
                },
                /*  repairStartDateVerify: function (value) {
                    if (value == "" || value == null) {
                        return '维修开始时间不能为空';
                    }
                },
                faultDescVerify: function (value) {
                    if (value == "" || value == null) {
                        return '故障描述不能为空';
                    }

                },*/
                repairShopQuotationVerify: function (value) {
                    var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                /*repairContentVerify: function (value) {
                    if (value == "" || value == null) {
                        return '维修内容不能为空';
                    }
                },*/
                userPayVerify: function (value) {
                    var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
                    /*if (value == "" || value == null) {
                        return '维修价格用户支付金额不能为空';
                    }*/
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                platformPayVerify: function (value) {
                    var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                insurancePayVerify: function (value) {
                    var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
                    if(value != "" &&  value!= null){
                        if(!reg.test(value)){
                            return '金额输入有误请重新输入';
                        }
                    }
                },
                /* isSpareCarVerify: function (value) {
                     if (value == "" || value == null) {
                         return '是否提供备用车不能为空';
                     }
                 },
                 spareCarNoVerify: function (value) {
                     if (value == "" || value == null) {
                         return '备用车车牌号不能为空';
                     }
                 }*/

            });
            form.render();
    });
    //是否提供备用车
    layui.form.on('select(isSpareCar)', function (data) {
        vm.carRepairOrder.isSpareCar = data.value;
        //如果备用车选择否则清空备用车车牌号
        if(data.value=="2"){
            vm.carRepairOrder.spareCarNo="";
        }

    });

    layui.form.on('select(costSettlement)', function (data) {
        vm.carRepairOrder.costSettlement = data.value;
    });

    //维修开始时间
    layui.use('laydate', function(){
        var laydate = layui.laydate;
        //维修开始时间
        laydate.render({
            elem: '#repairStartDate',
            trigger: 'click',
            done: function (value, date, endDate) {
                vm.carRepairOrder.repairStartDate=value;
            }
        });

        //维修结束时间
        laydate.render({
            elem: '#repairEndDate',
            trigger: 'click',
            done: function (value, date, endDate) {
                vm.carRepairOrder.repairEndDate=value;
            }
        });
    });

    //维修厂报价
    $("#repairShopQuotation").blur(function(){
        var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        if((vm.carRepairOrder.repairShopQuotation!=undefined) && (vm.carRepairOrder.repairShopQuotation !="") && (!reg.test(vm.carRepairOrder.repairShopQuotation))){
            alert("金额输入有误请重新输入");
            vm.carRepairOrder.repairShopQuotation="";
        }

    });

    //金额输入后进行计算
    $("#userPayId").blur(function(){
        var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        if(reg.test(vm.carRepairOrder.userPay)){
            amountAccumulation();
        }else if((vm.carRepairOrder.userPay!=undefined) && (vm.carRepairOrder.userPay !="") && (!reg.test(vm.carRepairOrder.userPay))){
            alert("金额输入有误请重新输入");
            vm.carRepairOrder.userPay="";
        }else if(vm.carRepairOrder.userPay==""){
            amountAccumulation();
        }

    });
    $("#platformPayId").blur(function(){
        var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        if(reg.test(vm.carRepairOrder.platformPay)){
            amountAccumulation();
        }else if((vm.carRepairOrder.platformPay!=undefined) && (vm.carRepairOrder.platformPay !="") && (!reg.test(vm.carRepairOrder.platformPay))){
            alert("金额输入有误请重新输入");
            vm.carRepairOrder.platformPay="";
        }else if(vm.carRepairOrder.platformPay==""){
            amountAccumulation();
        }
    });

    $("#insurancePayId").blur(function(){
        var reg=/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
        if(reg.test(vm.carRepairOrder.insurancePay)){
            amountAccumulation();
        }else if((vm.carRepairOrder.insurancePay!=undefined) && (vm.carRepairOrder.insurancePay!="") && (!reg.test(vm.carRepairOrder.insurancePay))){
            alert("金额输入有误请重新输入");
            vm.carRepairOrder.insurancePay="";
        }else if(vm.carRepairOrder.insurancePay==""){
            amountAccumulation();
        }
    });

    //附件上传
    layui.upload.render({
        elem: '#addFile',
        url: baseURL + 'file/uploadInsuranceFile',
        data: {'path':'carrepairorder'},
        field:'files',
        auto:true,
        size: 50*1024*1024,
        accept: 'file', //普通文件
        acceptMime: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg,.zip,.rar',
        exts: 'pdf|doc|docx|xls|xlsx|jpg|png|jpeg|zip|rar', //
        multiple: true,
        number:20,
        done: function (res) {
            if (res.code != '0') {
                layer.msg('上传失败', {icon: 5});
                vm.delFile(fileIdTmp);
                fileIdTmp = null;
                return false;
            }
            res.data.forEach(function (value) {
                var extIndex = value.resultFilePath.lastIndexOf('.');
                var ext = value.resultFilePath.slice(extIndex);
                var fileNameNotext = value.fileName;
                var regExt = /png|jpg|jpeg/;
                var fileType = regExt.test(ext) ? 1 : 0;
                fileIdTmp = vm.fileLst.length + '_' + uuid(60);
                var fileTmp = {
                    id: fileIdTmp,
                    operationId:sessionStorage.getItem("userId"),
                    operationName:sessionStorage.getItem("username"),
                    nameDesc: '维修附件',
                    nameAccessory: fileNameNotext,
                    nameFile: fileNameNotext,
                    nameExt: ext,
                    typeFile: fileType,
                    url: value.resultFilePath
                };
                vm.fileLst.push(fileTmp);
                vm.fileLstId = 'fileLstId_' + uuid(6);
            });
            fileIdTmp = null;
        },
        error: function () {
            RemoveLoading();
            layer.msg('上传失败', {icon: 5});
            vm.delFile(fileIdTmp);
            fileIdTmp = null;
        }
    });

    layui.upload.render({
        elem: '#addFile2',
        url: baseURL + 'file/uploadFile',
        data: {'path':'processApprove'},
        field:'files',
        auto:true,
        size: 50*1024*1024,
        accept: 'file', //普通文件
        acceptMime: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg,.zip,.rar',
        exts: 'pdf|doc|docx|xls|xlsx|jpg|png|jpeg|zip|rar', //
        multiple: true,
        number:20,
        choose: function(obj){
            // PageLoading();
            obj.preview(function(index, file, result){
                var fileName = file.name;
                var extIndex = fileName.lastIndexOf('.');
                var ext = fileName.slice(extIndex);
                var fileNameNotext = fileName.slice(0, extIndex);
                var regExt = /png|jpg|jpeg/;
                var fileType = regExt.test(ext) ? 1:0;
                fileIdTmp = vm.fileLst2.length + '_' + uuid(60);
                var fileTmp={
                    id: fileIdTmp,
                    operationId:sessionStorage.getItem("userId"),
                    operationName:sessionStorage.getItem("username"),
                    nameDesc:'审批附件',
                    nameAccessory:fileNameNotext,
                    nameFile:fileName,
                    nameExt:ext,
                    typeFile:fileType,
                };
                vm.fileLst2.push(fileTmp);
            });
        },
        done: function (res) {
            // RemoveLoading();
            if (res.code == '0') {
                vm.fileLst2.forEach(function (value) {
                    if (value.id === fileIdTmp) value.url = res.data[0];
                });
                vm.fileLstId2 = 'fileLstId_' + uuid(6);
            } else {
                layer.msg('上传失败', {icon: 5});
                vm.delFile2(fileIdTmp);
            }
            fileIdTmp = null;
        },
        error: function () {
            RemoveLoading();
            layer.msg('上传失败', {icon: 5});
            vm.delFile2(fileIdTmp);
            fileIdTmp = null;
        }
    });

    //保存按钮监听
    layui.form.on('submit(saveOrUpdate)', function(){
        vm.saveOrUpdate();
        return false;
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        //车辆信息数据源（选车子页面传过来）
        carInforData:{},
        //维修单保存信息数据源
        carRepairOrder:{},
        fileLst:[],
        fileLstId: '0',
        fileLst2:[],
        fileLstId2: '0',
        boxShow: false,
        boxInputShow: false,
        boxTitle: '',
        boxMark: '',
        boxHolder: '',
        boxTxt: '',
        viewTag:'edit',
        recallNodeName:null,
        processApproveForm:{},
        bpmChartDtoList: [],
        nodeType:null,
        instanceStatus:null
    },
    created: function () {
        var _this = this;
        var param = parent.layer.boxParams.boxParams;
        $.ajaxSettings.async = false;
        if(param){
            _this.recallNodeName = param.recallName;
            _this.viewTag = param.viewTag;
            _this.instanceStatus = param.instanceStatus;
            _this.processApproveForm = param;

            //初始化加载保险公司下拉列表
            if(_this.viewTag != 'edit'){
                $.get(baseURL + "activity/bpmChart",{processKey:param.processKey,instanceId:param.instanceId}, function (r) {
                    if (r.code == 0){
                        _this.bpmChartDtoList = r.bpmChart;
                    }
                });
            }
            $.get(baseURL + "activity/getNodeType",{instanceId:param.instanceId},function(r){
                _this.nodeType = r.nodeType;
            });
        }

        var id = window.localStorage.getItem("id");
        if(id != null && id != '' && id != undefined){
            $.get(baseURL + "carrepairorder/carrepairorder/info/"+id,function(r){
                _this.carRepairOrder=r.carRepairOrder;
                _this.fileLst = r.carRepairOrder.fileLst;
                _this.carRepairOrder = Object.assign({}, _this.carRepairOrder, {
                    carNo:r.carRepairOrder.carPlateNo,
                    rentTypeStr:r.carRepairOrder.carPurpose,
                    departureNo:r.carRepairOrder.orderNo,
                    belongCompanyName:r.carRepairOrder.deptName,
                    sumOdograph:r.carRepairOrder.mileage,
                    cityName:r.carRepairOrder.cityName,
                    customerName:r.carRepairOrder.customer,
                    depotName:r.carRepairOrder.depotName,
                    depotId:r.carRepairOrder.depotId
                });
            });
        }

        $.ajaxSettings.async = true;
    },
    updated: function () {
        layui.form.render();
    },
    methods: {
        requestAction: function (action,type) {
            PageLoading();
            vm.processApproveForm.processOperationType = type;
            vm.processApproveForm.businessId = window.localStorage.getItem("id");
            vm.processApproveForm.approveContent = vm.boxTxt;
            vm.processApproveForm.approveFileList=vm.fileLst2;
            vm.carRepairVoData = {
                processApproveForm:vm.processApproveForm,
                carRepairOrder:vm.carRepairOrder
            }
            var closeBox = false;
            $.ajax({
                type: "POST",
                url: baseURL + "carrepairorder/carrepairorder/" + action,
                contentType: "application/json",
                async:false,
                data: JSON.stringify(vm.carRepairVoData),
                success: function (r) {
                    RemoveLoading();
                    if (parseInt(r.code) === 0) {
                        alert('操作成功', function () {
                            closeBox = true;
                            layer.closeAll();
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.vm.reload();
                            parent.layer.close(index);
                        });
                    } else {
                        closeBox = false;
                        alert(r.msg);
                    }
                }
            });
            return closeBox;
        },
        showBox: function (submit) {
            vm.boxTxt = '';
            var index = layer.open({
                title: vm.boxTitle,
                type: 1,
                area: ['90%', '95%'],
                btn:['取消','确定'] ,
                content: $("#boxShow"),
                btnAlign: 'c',
                end: function(){
                    vm.boxShow = false;
                    vm.fileLst2=[];
                    layer.close(index);
                },
                btn1:function (index, layero) {
                    vm.boxShow = false;
                    vm.fileLst2=[];
                    layer.close(index);
                },
                btn2:function (index, layero) {
                    return submit();
                }
            });
            vm.boxShow = true;
        },
        approve:function(){
            vm.boxTitle = '审核通过';
            vm.boxMark = '审核反馈';
            vm.boxHolder = '可以输入审核意见/选填';
            vm.boxInputShow = true;
            vm.showBox(function () {
                return vm.requestAction('handle', 4);
            });
        },
        reject:function(){
            vm.boxTitle = '审核驳回-驳回' + vm.recallNodeName + '节点';
            vm.boxMark = '审核反馈';
            vm.boxHolder = '可以输入审核意见/必填';
            vm.boxInputShow = true;
            vm.showBox(function () {
                if (vm.boxTxt == null || vm.boxTxt == ''){
                    alert('请输入审核意见');
                    return false;
                }
                return vm.requestAction('handle', 3);
            });
        },
        reedit:function(){
            vm.viewTag = 'reedit';
        },
        getFileData:function (data){
            let param={
                data:data
            }
            var index = layer.open({
                title: "查看",
                type: 2,
                boxParams: param,
                content: tabBaseURL +"modules/common/approvefileview.html",
                end: function () {
                    layer.close(index);
                }
            });
            layer.full(index);
        },
        sendEditInfor:function(id){
            //清空数据源
            vm.carRepairOrder={};
            $.ajax({
                type: "POST",
                url: baseURL + "carrepairorder/carrepairorder/info/"+id,
                contentType: "application/json",
                data: {},
                success: function(r){
                    vm.carRepairOrder=r.carRepairOrder;
                    vm.fileLst = r.carRepairOrder.fileLst;
                    vm.carRepairOrder = Object.assign({}, vm.carRepairOrder, {
                        //车牌号
                        carNo:r.carRepairOrder.carPlateNo,
                        //车辆用途
                        rentTypeStr:r.carRepairOrder.carPurpose,
                        //车辆订单号
                        departureNo:r.carRepairOrder.orderNo,
                        //车辆所属公司
                        belongCompanyName:r.carRepairOrder.deptName,
                        //车辆当前里程数
                        sumOdograph:r.carRepairOrder.mileage,
                        //车辆所在城市
                        cityName:r.carRepairOrder.cityName,
                        //客户名称
                        customerName:r.carRepairOrder.customer,
                        //所属仓库
                        depotName:r.carRepairOrder.depotName,

                        depotId:r.carRepairOrder.depotId
                    });
                }
            });
        },
        //选择车牌号
        selectCarNo:function(){
            var index = layer.open({
                title: "选择车牌号",
                type: 2,
                content: tabBaseURL + "modules/common/selectcar.html",
                end: function(){
                    var carId=vm.carInforData.carId;
                    if(carId!=null && carId!='' && carId!=undefined){
                        vm.getCarBasicInforByCarNo(carId);
                    }


                }
            });
            layer.full(index);

        },
        //选择车架号
        selectVinNo:function(){
            var index = layer.open({
                title: "选择车架号",
                type: 2,
                content: tabBaseURL + "modules/common/selectcar.html",
                end: function(){
                    var vinNo=vm.carInforData.vinNo;
                    if(vinNo!=null && vinNo!=''&& vinNo!=undefined){
                        vm.getCarBasicInforByVinNo(vinNo);
                    }

                }
            });
            layer.full(index);

        },
        //根据车牌号查询基本信息
        getCarBasicInforByCarNo:function (carId) {
            $.ajax({
                type: "POST",
                url: baseURL + "car/tcarbasic/getCarBasicInforByCarNo/"+carId,
                contentType: "application/json",
                data: {},
                success: function(r){
                     
                    //车牌号
                    vm.carRepairOrder.carNo=r.baseInfor.carNo;
                    vm.carRepairOrder.vinNo=r.baseInfor.vinNo;
                    vm.carRepairOrder.carBrandModelName=r.baseInfor.carBrandModelName;
                    vm.carRepairOrder.customerName=r.baseInfor.customerName;
                    vm.carRepairOrder.carStatus =r.baseInfor.carStatus;
                    vm.carRepairOrder.carStatusStr=r.baseInfor.carStatusStr;
                    // vm.carRepairOrder.departureNo=r.baseInfor.departureNo;
                    vm.carRepairOrder.departureNo=r.baseInfor.carOrderNo;
                    vm.carRepairOrder.belongCompanyName=r.baseInfor.belongCompanyName;
                    vm.carRepairOrder.timeStartRent=r.baseInfor.timeStartRent;
                    vm.carRepairOrder.timeFinishRent=r.baseInfor.timeFinishRent;
                    vm.carRepairOrder.sumOdograph=r.baseInfor.sumOdograph;
                    vm.carRepairOrder.rentTypeStr=r.baseInfor.rentTypeStr;
                    vm.carRepairOrder.cityName=r.baseInfor.cityName;
                    vm.carRepairOrder.depotName=r.baseInfor.carDepotName;
                    vm.carRepairOrder.depotId=r.baseInfor.carDepotId;
                    vm.carRepairOrder.carId=r.baseInfor.carId;

                }
            });
        },
        //根据车架号查询基本信息
        getCarBasicInforByVinNo:function (vinNo) {
            $.ajax({
                type: "POST",
                url: baseURL + "car/tcarbasic/getCarBasicInforByVinNo/"+vinNo,
                contentType: "application/json",
                data: {},
                success: function(r){
                    vm.carRepairOrder.carNo=r.baseInfor.carNo;
                    vm.carRepairOrder.vinNo=r.baseInfor.vinNo;
                    vm.carRepairOrder.carBrandModelName=r.baseInfor.carBrandModelName;
                    vm.carRepairOrder.customerName=r.baseInfor.customerName;
                    vm.carRepairOrder.carStatus=r.baseInfor.carStatus;
                    vm.carRepairOrder.carStatusStr=r.baseInfor.carStatusStr;
                    // vm.carRepairOrder.departureNo=r.baseInfor.departureNo;
                    vm.carRepairOrder.departureNo=r.baseInfor.carOrderNo;
                    vm.carRepairOrder.belongCompanyName=r.baseInfor.belongCompanyName;
                    vm.carRepairOrder.timeStartRent=r.baseInfor.timeStartRent;
                    vm.carRepairOrder.timeFinishRent=r.baseInfor.timeFinishRent;
                    vm.carRepairOrder.sumOdograph=r.baseInfor.sumOdograph;
                    vm.carRepairOrder.rentTypeStr=r.baseInfor.rentTypeStr;
                    vm.carRepairOrder.cityName=r.baseInfor.cityName;
                    vm.carRepairOrder.depotName=r.baseInfor.carDepotName;
                    vm.carRepairOrder.depotId=r.baseInfor.carDepotId;
                    vm.carRepairOrder.carId=r.baseInfor.carId;
                }
            });
        },
        //取消
        cancel: function(){
            parent.layer.closeAll();
        },
        //保存修改方法
        saveOrUpdate: function (event) {
            vm.carRepairOrder.carPlateNo=vm.carRepairOrder.carNo;
            vm.carRepairOrder.orderNo=vm.carRepairOrder.departureNo;
            vm.carRepairOrder.carPurpose=vm.carRepairOrder.rentType;
            vm.carRepairOrder.factoryId=vm.carRepairOrder.deptId;
            vm.carRepairOrder.factoryName=vm.carRepairOrder.deptName;
            vm.carRepairOrder.customer = vm.carRepairOrder.customerName;
            vm.carRepairOrder.viewTag = vm.viewTag;
            vm.carRepairOrder.instanceId = vm.processApproveForm.instanceId;
            var url ="carrepairorder/carrepairorder/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.carRepairOrder),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            parent.layer.closeAll();
                            parent.vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        delFile: function (id) {
            for(var i = 0 ;i<vm.fileLst.length;i++) {
                if(vm.fileLst[i].id === id) {
                    vm.fileLst.splice(i,1);
                    i= i-1;
                }
            }
        },
        delFile2: function (id) {
            for(var i = 0 ;i<vm.fileLst2.length;i++) {
                if(vm.fileLst2[i].id === id) {
                    vm.fileLst2.splice(i,1);
                    i= i-1;
                }
            }
        },
    },

})
function amountAccumulation(){
    $.ajax({
        type: "POST",
        url: baseURL + 'carrepairorder/carrepairorder/amountAccumulation',
        contentType: "application/json",
        data:JSON.stringify(vm.carRepairOrder),
        success: function(r){
            vm.carRepairOrder = Object.assign({}, vm.carRepairOrder, {totalPay: r.amountAccumulation});
        }
    });
}


